Page({
  data: {
    tagId: null,
    tagName: '',
    type: '',
    recipeList: [],
    page: 1,
    pageSize: 10,
    loading: false,
    hasMore: true
  },

  onLoad(options) {
    const { tagId, tagName, type } = options;
    this.setData({
      tagId: tagId,
      tagName: tagName,
      type: type
    });
    
    // 设置页面标题
    wx.setNavigationBarTitle({
      title: tagName || '菜谱列表'
    });
    
    // 加载菜谱数据
    this.loadRecipeList();
  },

  // 加载菜谱列表
  loadRecipeList() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ 
      loading: true
    });

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    // 根据类型调用不同的接口
    let url = '';
    let data = {
      pageNum: this.data.page,
      pageSize: this.data.pageSize
    };

    if (this.data.type === 'scene') {
      // 场景标签菜谱 - 使用新的标签接口
      url = `http://localhost/dev-api/recipes/tags/recipes/${this.data.tagId}`;
    } else {
      // 默认菜谱列表
      url = 'http://localhost/dev-api/recipes/recipes/list';
    }

    // 只有当参数有效时才发送请求
    if (!url) {
      this.setData({ loading: false });
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: url,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: data,
      success: (res) => {
        this.setData({ loading: false });
        
        if (res.data.code === 200 && res.data && res.data.rows) {
          const newRecipes = res.data.rows || [];
          
          // 处理菜谱数据
          const processedRecipes = newRecipes.map(recipe => {
            // 根据媒体类型处理封面图
            let imageUrl = 'https://picsum.photos/300/200?random=default';
            if (recipe.mediaType === 2) {
              // 视频类型：使用videoDescription作为封面图，如果没有则使用默认图片
              imageUrl = recipe.videoDescription 
                ? `http://localhost:8080${recipe.videoDescription}` 
                : 'https://picsum.photos/300/200?random=video';
            } else if (recipe.mediaType === 1) {
              // 图片类型：使用coverUrl作为封面图
              imageUrl = recipe.coverUrl 
                ? `http://localhost:8080${recipe.coverUrl}` 
                : 'https://picsum.photos/300/200?random=image';
            }

            return {
              id: recipe.id,
              title: recipe.title || '未知菜谱',
              imageUrl: imageUrl,
              authorName: recipe.users?.nickname || '未知用户',
              collectCount: recipe.collectCount || 0,
              likeCount: recipe.likeCount || 0,
              viewCount: recipe.viewCount || 0,
              mediaType: recipe.mediaType || 1
            };
          });

          if (this.data.page === 1) {
            // 第一页，直接替换数据
            this.setData({
              recipeList: processedRecipes,
              page: this.data.page + 1,
              hasMore: newRecipes.length === this.data.pageSize
            });
          } else {
            // 后续页面，追加数据
            this.setData({
              recipeList: [...this.data.recipeList, ...processedRecipes],
              page: this.data.page + 1,
              hasMore: newRecipes.length === this.data.pageSize
            });
          }
        } else {
          wx.showToast({
            title: '暂无数据',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        this.setData({ loading: false });
        console.error('获取菜谱列表失败:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    });
  },

  // 菜谱点击
  onRecipeTap(e) {
    const recipeId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/index/pages/detail/detail?id=${recipeId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      recipeList: [],
      page: 1,
      hasMore: true
    });
    
    this.loadRecipeList();
    
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadRecipeList();
  }
});
